<template>
  <div class="ticket-container">
    <!-- 核销表单 -->
    <el-card class="verify-form">
      <template #header>
        <div class="card-header">
          <el-icon><Ticket /></el-icon>
          <span>门票核销</span>
        </div>
      </template>
      
      <div class="verify-methods">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="订单号核销" name="order">
            <el-form :model="verifyForm" :rules="rules" ref="formRef">
              <el-form-item prop="orderNumber" label="订单号">
                <el-input v-model="verifyForm.orderNumber" placeholder="请输入订单号"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleVerify" :loading="verifyLoading">核销门票</el-button>
                <el-button type="info" @click="handleOrderQuery">查询订单</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="扫码核销" name="scan">
            <div class="scan-container">
              <div class="scan-tip">
                <el-alert
                  title="请将二维码/条形码对准扫码区域"
                  type="info"
                  show-icon
                  :closable="false"
                />
              </div>
              <div class="scan-box">
                <!-- 这里可以添加扫码组件或示意图 -->
                <div class="scan-placeholder">
                  <el-icon><Camera /></el-icon>
                  <p>扫码区域</p>
                </div>
              </div>
              <div class="scan-action">
                <el-button type="primary" @click="handleScan">模拟扫码</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 订单详情卡片，仅在查询到订单时显示 -->
    <el-card v-if="orderDetail.show" class="order-detail-card">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>订单详情</span>
        </div>
      </template>
      
      <div class="order-info">
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.data.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="景区名称">{{ orderDetail.data.scenicName }}</el-descriptions-item>
          <el-descriptions-item label="门票数量">{{ orderDetail.data.ticketCount }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ orderDetail.data.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="游玩日期">{{ formatDate(orderDetail.data.playDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(orderDetail.data.state)">
              {{ getStatusText(orderDetail.data.state) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="order-actions">
          <el-button 
            type="success" 
            size="large" 
            @click="handleVerifyOrder(orderDetail.data.orderNumber)"
            :disabled="orderDetail.data.state !== 1"
            :loading="verifyLoading"
          >
            核销门票
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 核销记录 -->
    <el-card class="verify-records">
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>核销记录</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNumber" placeholder="请输入订单号"></el-input>
          </el-form-item>
          <el-form-item label="景区名称">
            <el-input v-model="searchForm.scenicName" placeholder="请输入景区名称"></el-input>
          </el-form-item>
          <el-form-item label="核销日期">
            <el-date-picker
              v-model="searchForm.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="orderNumber" label="订单号" width="180" />
        <el-table-column prop="scenicName" label="景区名称" width="180" />
        <el-table-column prop="ticketCount" label="门票数量" width="100" align="center" />
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.totalAmount">¥{{ scope.row.totalAmount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="核销时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100" align="center">
          <template #default="scope">
            <el-tag type="success">已完成</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 核销结果弹窗 -->
    <el-dialog
      v-model="resultDialog.show"
      :title="resultDialog.success ? '核销成功' : '核销失败'"
      width="30%"
      center
    >
      <div class="result-content">
        <div class="result-icon">
          <el-icon v-if="resultDialog.success" class="success-icon"><SuccessFilled /></el-icon>
          <el-icon v-else class="error-icon"><CircleCloseFilled /></el-icon>
        </div>
        <div class="result-message">
          {{ resultDialog.message }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resultDialog.show = false">关闭</el-button>
          <el-button type="primary" @click="closeResultAndRefresh" v-if="resultDialog.success">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Ticket, List, Camera, Document, SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { ticketAPI, orderAPI } from '@/utils/api'

// 活动选项卡
const activeTab = ref('order')

// 核销表单
const formRef = ref(null)
const verifyForm = reactive({
  orderNumber: ''
})
const rules = {
  orderNumber: [
    { required: true, message: '请输入订单号', trigger: 'blur' }
  ]
}

// 核销加载状态
const verifyLoading = ref(false)

// 订单详情
const orderDetail = reactive({
  show: false,
  data: {
    orderNumber: '',
    scenicName: '',
    ticketCount: 0,
    totalAmount: 0,
    playDate: '',
    state: 0
  }
})

// 搜索表单
const searchForm = reactive({
  orderNumber: '',
  scenicName: '',
  date: []
})

// 表格数据
const tableData = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 核销结果弹窗
const resultDialog = reactive({
  show: false,
  success: false,
  message: ''
})

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '未设置';
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return dateStr;
  }
};

// 获取订单状态样式
const getStatusType = (state) => {
  const map = {
    0: 'danger',   // 待支付
    1: 'warning',  // 待使用
    2: 'success',  // 已完成
    3: 'info',     // 已取消
    4: 'primary'   // 已退款
  };
  return map[state] || 'info';
}

// 获取订单状态文本
const getStatusText = (state) => {
  const map = {
    0: '待支付',
    1: '待使用',
    2: '已完成',
    3: '已取消',
    4: '已退款'
  };
  return map[state] || '未知状态';
}

// 日期时间格式化函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知';
  
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return dateTimeStr;
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (err) {
    console.error('日期格式化错误:', err);
    return dateTimeStr;
  }
};

// 获取核销记录
const getVerifiedRecords = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };
  
  // 添加搜索条件
  if (searchForm.orderNumber) params.orderNumber = searchForm.orderNumber;
  if (searchForm.scenicName) params.scenicName = searchForm.scenicName;
  if (searchForm.date && searchForm.date.length > 0) {
    params.startDate = searchForm.date[0];
    params.endDate = searchForm.date[1];
  }
  
  // 使用状态为2(已完成)的订单作为已核销订单
  ticketAPI.getVerified(params).then(res => {
    if (res.data.code === 200) {
      const responseData = res.data.data;
      
      if (responseData.records) {
        // MyBatis Plus分页格式
        tableData.value = responseData.records;
        total.value = responseData.total;
      } else if (Array.isArray(responseData)) {
        // 数组格式
        tableData.value = responseData;
        total.value = responseData.length;
      } else {
        // 其他格式处理
        tableData.value = [];
        total.value = 0;
      }
      
      // 所有状态为2的订单都是已核销的
      tableData.value.forEach(item => {
        item.used = true;
      });
      
    } else {
      ElMessage.error(res.data.message || '获取核销记录失败');
      tableData.value = [];
      total.value = 0;
    }
  }).catch(err => {
    console.error('获取核销记录失败:', err);
    ElMessage.error('获取核销记录失败');
    tableData.value = [];
    total.value = 0;
  });
}

// 查询订单
const handleOrderQuery = () => {
  if (!verifyForm.orderNumber) {
    ElMessage.warning('请输入订单号');
    return;
  }
  
  // 使用订单详情接口查询
  orderAPI.getDetail(verifyForm.orderNumber).then(res => {
    if (res.data.code === 200) {
      const detail = res.data.data;
      
      // 设置订单详情数据
      orderDetail.data = {
        orderNumber: detail.orderNumber,
        scenicName: detail.scenicName,
        ticketCount: detail.ticketCount || 1,
        totalAmount: detail.totalAmount,
        playDate: detail.playDate,
        state: detail.state
      };
      
      orderDetail.show = true;
      
      // 检查订单状态，只有状态为1(待使用)的订单才能核销
      if (orderDetail.data.state !== 1) {
        ElMessage.warning(`该订单状态为"${getStatusText(orderDetail.data.state)}"，无法核销`);
      }
    } else {
      ElMessage.error(res.data.message || '订单查询失败');
      orderDetail.show = false;
    }
  }).catch(err => {
    console.error('订单查询失败:', err);
    ElMessage.error('订单查询失败，请检查订单号是否正确');
    orderDetail.show = false;
  });
}

// 核销处理
const handleVerify = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      verifyTicket(verifyForm.orderNumber);
    }
  });
}

// 核销指定订单
const handleVerifyOrder = (orderNumber) => {
  verifyTicket(orderNumber);
}

// 模拟扫码
const handleScan = () => {
  // 模拟生成一个随机的订单号
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
  const orderNumber = `T${randomNum}`;
  
  ElMessageBox.prompt('请输入模拟的订单号', '模拟扫码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: orderNumber,
    inputPattern: /\S+/,
    inputErrorMessage: '订单号不能为空'
  }).then(({ value }) => {
    verifyTicket(value);
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消了模拟扫码');
  });
}

// 核销门票的通用方法
const verifyTicket = (orderNumber) => {
  if (!orderNumber) {
    ElMessage.warning('请输入订单号');
    return;
  }
  
  verifyLoading.value = true;
  console.log('准备核销门票，订单号:', orderNumber);
  
  // 使用核销接口
  ticketAPI.verify(orderNumber).then(res => {
    console.log('核销门票响应:', res);
    if (res.data.code === 200) {
      resultDialog.success = true;
      resultDialog.message = `订单 ${orderNumber} 核销成功！`;
      resultDialog.show = true;
      
      // 清空输入框
      verifyForm.orderNumber = '';
      // 隐藏订单详情
      orderDetail.show = false;
    } else {
      resultDialog.success = false;
      resultDialog.message = res.data.message || '门票核销失败';
      resultDialog.show = true;
    }
  }).catch(err => {
    console.error('门票核销失败:', err);
    resultDialog.success = false;
    resultDialog.message = '门票核销失败，请检查订单号是否正确';
    resultDialog.show = true;
  }).finally(() => {
    verifyLoading.value = false;
  });
}

// 关闭结果弹窗并刷新数据
const closeResultAndRefresh = () => {
  resultDialog.show = false;
  getVerifiedRecords();
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  getVerifiedRecords();
}

const resetSearch = () => {
  searchForm.orderNumber = '';
  searchForm.scenicName = '';
  searchForm.date = [];
  currentPage.value = 1;
  getVerifiedRecords();
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  getVerifiedRecords();
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getVerifiedRecords();
}

onMounted(() => {
  getVerifiedRecords();
})
</script>

<style scoped>
.ticket-container {
  padding: 20px;
}

.verify-form {
  margin-bottom: 20px;
}

.order-detail-card {
  margin-bottom: 20px;
}

.verify-records {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.verify-methods {
  padding: 10px 0;
}

.scan-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.scan-tip {
  width: 100%;
}

.scan-box {
  width: 300px;
  height: 200px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.scan-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.scan-placeholder .el-icon {
  font-size: 50px;
  margin-bottom: 10px;
}

.scan-action {
  margin-top: 10px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.result-icon {
  font-size: 60px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.result-message {
  font-size: 16px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>